package cn.school.stu.evaluation.service.impl;

import cn.school.classManage.dao.SchoolClassDao;
import cn.school.classManage.entity.ClassCurriculumDetail;
import cn.school.classManage.entity.ClassCurriculumMain;
import cn.school.classManage.vo.SchoolClassVO;
import cn.school.common.api.CommonResult;
import cn.school.common.exception.ApiException;
import cn.school.common.utils.SysUserUtils;
import cn.school.educational.entity.Subject;
import cn.school.stu.evaluation.dao.StuEvaDataDao;
import cn.school.stu.evaluation.dao.StuEvaIndicatorDao;
import cn.school.stu.evaluation.dao.StuEvaPlanDao;
import cn.school.stu.evaluation.dao.StuEvaTaskDao;
import cn.school.stu.evaluation.entity.StuEvaData;
import cn.school.stu.evaluation.entity.StuEvaIndicator;
import cn.school.stu.evaluation.entity.StuEvaPlan;
import cn.school.stu.evaluation.entity.StuEvaTask;
import cn.school.stu.evaluation.service.StuEvaDataService;
import cn.school.student.dao.StudentInfoDao;
import cn.school.student.entity.StudentInfo;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: lx
 * @date: 2023/5/26 10:22
 * @description:
 */
@Service
public class StuEvaDataServiceImpl extends ServiceImpl<StuEvaDataDao, StuEvaData> implements StuEvaDataService {

    @Autowired
    StuEvaDataDao stuEvaDataDao;

    @Autowired
    StuEvaTaskDao stuEvaTaskDao;

    @Autowired
    StuEvaPlanDao stuEvaPlanDao;

    @Autowired
    StuEvaIndicatorDao stuEvaIndicatorDao;

    @Resource
    StudentInfoDao studentInfoDao;

    @Override
    public int createStuEvaData(StuEvaData stuEvaData) {
        return 0;
    }

    @Override
    @Transactional
    public boolean createStuEvaDataBatch(List<StuEvaData> stuEvaDataList) throws ApiException {
        int stuCount = 0;
        if (stuEvaDataList.size() > 0) {
            for (StuEvaData item : stuEvaDataList) {
                Long taskId = stuEvaDataList.get(0).getTaskId();
                LambdaQueryWrapper<StuEvaData> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(StuEvaData::getTaskId, taskId);
                wrapper.eq(StuEvaData::getStudentId, item.getStudentId());
                int delete = stuEvaDataDao.delete(wrapper);
            }
            //获取当前任务下的考评班级有多少学生
            LambdaQueryWrapper<StudentInfo> stuWrapper = new LambdaQueryWrapper<>();
            stuWrapper.eq(StudentInfo::getClassId, stuEvaDataList.get(0).getClassId());
            List<StudentInfo> studentInfos = studentInfoDao.selectList(stuWrapper);
            stuCount = studentInfos.size();
        } else {
            //空数据
            throw new ApiException("提交的数据为空，请先保存后提交");
        }

        //插入考评数据
        int ids = stuEvaDataDao.createStuEvaDataBatch(stuEvaDataList);
        //匹配数量来修改考评任务的状态
        LambdaQueryWrapper<StuEvaData> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(StuEvaData::getTaskId, stuEvaDataList.get(0).getTaskId());
        List<StuEvaData> stuEvaData = stuEvaDataDao.selectList(wrapper2);
        if (stuEvaData.size() == stuCount) {
            StuEvaTask stuEvaTask = stuEvaTaskDao.selectById(stuEvaDataList.get(0).getTaskId());
            stuEvaTask.setEvaStatus("2");
            stuEvaTaskDao.updateById(stuEvaTask);
            //考评任务完成了，判断当前考评方案下是否还存在考评任务，如果不存在则修改状态，存在则跳过
            LambdaQueryWrapper<StuEvaTask> taskWrapper = new LambdaQueryWrapper<>();
            taskWrapper.eq(StuEvaTask::getStuEvaPlanId, stuEvaTask.getStuEvaPlanId());
            List<StuEvaTask> stuEvaTasks = stuEvaTaskDao.selectList(taskWrapper);
            //标记是否还有未开始评分的考评任务
            int flag = 0;
            for (StuEvaTask item : stuEvaTasks) {
                //存在有一个考评任务状态为“0”，即状态为待评分，则不对当前考评方案的状态进行修改
                if ("0".equals(item.getEvaStatus())) {
                    flag++;
                    break;
                }
            }
            if (flag == 0) {
                StuEvaPlan stuEvaPlan = stuEvaPlanDao.selectById(stuEvaTask.getStuEvaPlanId());
                stuEvaPlan.setState("0");
                stuEvaPlanDao.updateById(stuEvaPlan);
            }
        } else if (stuEvaData.size() < stuCount) {
            StuEvaTask stuEvaTask = stuEvaTaskDao.selectById(stuEvaDataList.get(0).getTaskId());
            stuEvaTask.setEvaStatus("1");
            stuEvaTaskDao.updateById(stuEvaTask);
        }

        //插入数据的量等于传入list长度，则true
        if (ids == stuEvaDataList.size()) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public List<StuEvaData> findStuEvaDataByStuId(Long stuId) {
        LambdaQueryWrapper<StuEvaData> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StuEvaData::getStudentId, stuId);
        List<StuEvaData> stuEvaDataList = stuEvaDataDao.selectList(wrapper);
        return stuEvaDataList;
    }

    @Override
    public List<StuEvaData> findStuEvaDataByTaskId(Long taskId) {
        LambdaQueryWrapper<StuEvaData> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StuEvaData::getTaskId, taskId);
        List<StuEvaData> stuEvaDataList = stuEvaDataDao.selectList(wrapper);
        return stuEvaDataList;
    }

    @Override
    public IPage<StuEvaData> findStuEvaDataPageList(StuEvaData vo) {
        int pageNum = vo.getPageNum();
        int pageSize = vo.getPageSize();
        int startNum = (pageNum - 1) * pageSize;
        String tenantId = SysUserUtils.getSysUser().getTenantId();
        int count = stuEvaDataDao.findStuEvaDataCount(vo, tenantId);
        List<StuEvaData> list = stuEvaDataDao.findStuEvaDataPageList(startNum, vo, tenantId);
        IPage<StuEvaData> page = new Page<>();
        page.setTotal(count);
        page.setRecords(list);
        return page;
    }

    @Override
    public CommonResult<List<StuEvaData>> importExcel(InputStream inputStream) throws IOException {

        XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
        //读取第一个sheet
        XSSFSheet sheet = workbook.getSheetAt(0);
        String classId = "";
        String termTimeID = "";
        ClassCurriculumMain mainEntity = new ClassCurriculumMain();
        List<ClassCurriculumDetail> detailList = new ArrayList<>();
        ClassCurriculumDetail detail = null;
        List<String> oneTitleList = new ArrayList<>();
        List<String> twoTitleList = new ArrayList<>();
        List<List<String>> totleList = new ArrayList<>();
        // 3.获取行
        for (int i = 0; i < sheet.getPhysicalNumberOfRows(); i++) {
            //获取每行的内容
            Row row = sheet.getRow(i);
            List<String> rowList = new ArrayList<>();
            if (i == 0) {
                for (int j = 0; j < row.getLastCellNum(); j++) {
                    Cell cell = row.getCell(j);
                    if (cell.getStringCellValue() instanceof String) {
                        oneTitleList.add(cell.getStringCellValue());
                    } else {
                        oneTitleList.add(cell.getNumericCellValue() + "");
                    }
                }
            } else if (i == 1) {
                //获取列名
                for (int j = 0; j < row.getLastCellNum(); j++) {
                    Cell cell = row.getCell(j);
                    if (cell.getStringCellValue() instanceof String) {
                        twoTitleList.add(cell.getStringCellValue());
                    } else {
                        twoTitleList.add(cell.getNumericCellValue() + "");
                    }
                }
            } else {
                for (int j = 0; j < row.getLastCellNum(); j++) {
                    Cell cell = row.getCell(j);
                    CellType cellType = cell.getCellTypeEnum();
                    String value = "";
                    switch (cellType) {
                        case NUMERIC://无
                            value = cell.getNumericCellValue() + "";
                            break;
                        case STRING://空值
                            value = cell.getStringCellValue();
                            break;
                    }

                    rowList.add(value);
                }
                totleList.add(rowList);
            }
        }
        System.out.println(oneTitleList);
        System.out.println(twoTitleList);
        System.out.println(totleList);


        List<StuEvaData> stuEvaDataList = new ArrayList<>();
        StuEvaData data = null;

        for (List<String> strings : totleList) {
            List<Map<String, String>> resultList = new ArrayList<>();
            Map<String, String> map = new HashMap<>();
            data = new StuEvaData();
            for (int i = 0; i < strings.size(); i++) {

                if (i == 0) {
                    data.setTaskId(Long.valueOf(strings.get(i)));
                } else if (i == 1) {
                    data.setEvaPlanName(strings.get(i));
                } else if (i == 2) {
                    data.setTermTimeName(strings.get(i));

                } else if (i == 3) {
                    data.setClassId(Long.valueOf(strings.get(i)));

                } else if (i == 4) {
                    data.setStudentName(strings.get(i));
                } else if (i == 5) {
                    data.setClassName(strings.get(i));
                } else if (i == 6) {
                    data.setStudentId(Long.valueOf(strings.get(i)));
                } else {
                    map = new HashMap<>();
                    map.put("indicator", oneTitleList.get(i));
                    map.put("grade", strings.get(i));
                    map.put("element", twoTitleList.get(i));
                    List<StuEvaIndicator> firstIndicators = stuEvaIndicatorDao.findStuEvaIndicatorByName(oneTitleList.get(i),
                            SysUserUtils.getSysUser().getTenantId());
                    //size不等于1代表有重名的一级指标
                    if (firstIndicators.size() == 1) {
                        StuEvaIndicator firstIndicator = firstIndicators.get(0);
                        //当前一级考评指标下是否存在二级指标
                        List<StuEvaIndicator> secondIndicators = stuEvaIndicatorDao.findStuEvaIndicatorByPid(firstIndicator.getId());
                        //存在二级指标
                        if (secondIndicators.size() > 0) {
                            List<StuEvaIndicator> indicators = stuEvaIndicatorDao.findStuEvaIndicatorByName(twoTitleList.get(i),
                                    SysUserUtils.getSysUser().getTenantId());
                            map.put("remark", indicators.get(0).getRemark());
                        } else {
                            //不存在二级指标
                            map.put("remark", firstIndicator.getRemark());
                        }
                    } else if (firstIndicators.size() > 1) {
//                        String taskId = oneTitleList.get(0);
//                        StuEvaTask stuEvaTask = stuEvaTaskDao.selectById(taskId);
//                        Long stuEvaPlanId = stuEvaTask.getStuEvaPlanId();
//                        LambdaQueryWrapper<StuEvaPlan> planWrapper = new LambdaQueryWrapper<>();
//                        planWrapper.eq(StuEvaPlan::getId,stuEvaPlanId);
//                        StuEvaPlan stuEvaPlan = stuEvaPlanDao.selectOne(planWrapper);
//                        String indicators = stuEvaPlan.getIndicators();
//                        String[] split = indicators.split(",");
//                        stuEvaIndicatorDao.findStuEvaIndicatorByIds(split);
                    }
                    resultList.add(map);

                }
            }
            data.setResult(JSON.toJSONString(resultList));
            stuEvaDataList.add(data);
        }
        return CommonResult.success(stuEvaDataList);

    }
}
